<template>
  <a-modal v-model:open="visible" :title="formTitle" @ok="onSubmit" @cancel="onClose">
    <a-form :model="form" :rules="rules" :label-col="{ sm: 4 }" ref="formRef">
      <a-form-item label="线路名称" name="name">
        <a-input v-model:value="form.name" placeholder="请输入线路名称" />
      </a-form-item>
      <a-form-item label="业务员" name="salesman_id" required>
        <Select name="Salesman" v-model:value="form.salesman_id" placeholder="请选择业务员" />
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-input v-model:value="form.remark" placeholder="请输入备注" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts" setup>
import _ from 'lodash'
import Select from '@/components/business/select/index.vue'
import { message } from 'ant-design-vue'
import { errorSentry } from '@/lib/error-sentry'
import { lineApi } from '@/api/business/data/line-api'
import { useLoadingStore } from '@/store/modules/loading-store'
const loadingStore = useLoadingStore()
// emit
const emit = defineEmits(['reload-list'])

// 组件ref
const formRef = ref()

const formDefault = {
  // 线路名称
  name: '',
  // 业务员
  salesman_id: undefined,
  // 备注
  remark: ''
}

const form = ref(_.cloneDeep(formDefault))
const rules = {
  name: [{ required: true, message: '请输入线路名称', trigger: 'blur' }],
  salesman_id: [{ required: true, message: '请选择业务员', trigger: 'blur' }]
}
// 是否展示抽屉
const visible = ref(false)

function showDrawer(rowData) {
  form.value = _.cloneDeep(formDefault)
  if (rowData && !_.isEmpty(rowData)) {
    form.value = _.pick(rowData, ['id', ...Object.keys(formDefault)])
  }
  visible.value = true
  nextTick(() => {
    formRef.value.clearValidate()
  })
}

function onClose() {
  form.value = formDefault
  visible.value = false
}

function onSubmit() {
  formRef.value
    .validate()
    .then(async () => {
      loadingStore.show()
      try {
        if (unref(form).id) {
          await lineApi.editLine(unref(form))
        } else {
          await lineApi.addLine(unref(form))
        }
        message.success('操作成功')
        onClose()
        emit('reload-list')
      } catch (error) {
        message.error(error.msg)
        errorSentry.captureError(error)
      } finally {
        loadingStore.hide()
      }
    })
    .catch((error) => {
      console.log('error', error)
      message.error('参数验证错误，请仔细填写表单数据!')
    })
}

defineExpose({
  showDrawer
})

// 表单标题
const formTitle = computed(() => (form.value.id ? '编辑' : '新增'))
</script>
